import { Context } from 'koa'

export default async (ctx: Context, next: () => Promise<void>) => {
  try {
    await next()
  } catch (err: any) {
    ctx.status = err.statusCode || err.status || 500
    ctx.body = {
      msg: err.message || 'Internal Server Error',
      code: 1001
    }
    // 可选：触发应用级别的错误事件
    ctx.app.emit('error', err, ctx)
  }
}
